<template>
  <div class="app-container">
    <el-form size="small" :inline="true" :model="searchForm" class="demo-form-inline">
      <!-- 动态生成表单项 -->
      <el-form-item v-for="field in fields" :key="field.name" :label="field.label">
        <el-input
          v-if="field.type === 'input'"
          v-model="searchForm[field.name]"
          clearable
          :placeholder="field.placeholder"
          @keyup.enter.native="search"
        />
        <el-select
          v-else-if="field.type === 'select'"
          v-model="searchForm[field.name]"
          :filterable="field.filterable"
          placeholder="请选择"
          clearable
          @change="search"
        >
          <el-option v-for="option in field.options" :key="option.value" :label="option.label" :value="option.value"/>
        </el-select>
        <el-date-picker
          v-else-if="field.type === 'daterange'"
          v-model="searchForm[field.name]"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange(field.name)"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>

      </el-form-item>
    </el-form>

    <div class="action-btns">
      <el-button-group>
        <el-button type="info" size="mini" icon="el-icon-refresh" @click="search">刷新</el-button>
        <el-button type="success" size="mini" icon="el-icon-plus" @click="$router.push({path:'roleForm'})">新增
        </el-button>
      </el-button-group>
      <el-button-group>
        <el-button type="primary" size="mini" icon="el-icon-menu" @click="showColumnSetting = true">字段配置</el-button>
      </el-button-group>

    </div>
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      tooltip-effect="dark"
      style="width: 100%"
      align="center"
      @selection-change="handleSelectionChange"
    >
      <!--      <el-table-column type="selection" width="55" align="center" prop="id"/>-->
      <el-table-column
        v-for="(item,index) in visibleColumns"
        :key="index"
        :align="item.align"
        :label="item.label"
        :min-width="item.minWidth"
        :prop="item.prop"
        show-overflow-tooltip
      >
        <template v-if="item.tags" v-slot:default="{scope, row}">
          <el-tag
            :type="item.tags[row[item.prop]].type"
            :color="item.tags[row[item.prop]].color"
            hit
          >{{ item.tags[row[item.prop]].label }}
          </el-tag>
        </template>
        <template v-else-if="item.type && item.type === 'image'" v-slot:default="{scope, row}">
          <img
            v-for="(image, index1) in [row[item.prop]]"
            :key="index1"
            :src="image"
            style="width: 50px; height: 50px; margin-right: 10px;"
          >
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" fixed="right" width="130">
        <template v-slot:default="{scope,row}">
          <el-row type="flex" justify="space-around">
            <el-button
              size="mini"
              type="primary"
              title="修改"
              icon="el-icon-edit"
              circle
              @click="$router.push({path:'roleForm',query:{id:row.role_id}})"
            />
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-s-check"
              circle
              @click="$router.push({path:'roleAuths',query:{id:row.role_id}})"
            />
             <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="del(row.role_id)"></el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <!-- 字段设置对话框 -->
    <el-dialog title="字段设置" :visible.sync="showColumnSetting" width="80%">
      <el-checkbox v-model="isAllChecked" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选
      </el-checkbox>
      <el-checkbox-group v-model="checkList" @change="updateVisibleColumns">
        <el-checkbox
          v-for="column in el_table_column"
          :key="column.prop"
          border
          size="small"
          :label="column.label"
        >
          {{ column.label }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showColumnSetting = false">取 消</el-button>
        <el-button class="bs-left-10" type="primary" @click="closeVisibleColumns">确 定</el-button>
      </span>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      :page-sizes="[10, 20, 30, 50, 100]"
      @pagination="fetchData"
    />
  </div>

</template>

<script>
import api from '@/api/role'
import Pagination from '@/components/Pagination'

export default {
  components: {
    Pagination
  },
  filters: {},
  data() {
    return {
      fields: [
        { name: 'keyword', label: '关键词', type: 'input', placeholder: '搜索' }
      ],
      multipleSelection: [],
      el_table_column: [],
      list: null,
      listLoading: true,
      total: 0,
      searchForm: {
        type: '',
        keyword: '',
        sort: '',
        created_time: ''
      },

      isAllChecked: true, // 是否全选
      isIndeterminate: true, // 全选框是否为不确定状态
      checkList: [], // 选择的字段名称（标签）
      showColumnSetting: false,
      visibleColumns: [] // 当前显示的列配置
    }
  },
  computed: {
    listQuery() {
      return {
        type: this.type, // 根据prop动态设置type
        page: this.$route.query.page || 1,
        limit: this.$route.query.limit || 10,
        sort: this.$route.query.sort || ''
      }
    }
  },
  created() {
    if (this.$route.query.hasOwnProperty('user_id')) {
      this.searchForm.user_id = this.$route.query.user_id
      this.listQuery = Object.assign(this.listQuery, this.searchForm)
    }
    this.fetchData()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },

    updateVisibleColumns() {
      // 更新可见列
      this.visibleColumns = this.el_table_column.filter(column => this.checkList.includes(column.label))
    },
    closeVisibleColumns() {
      this.showColumnSetting = false
    },
    handleCheckAllChange(val) {
      this.checkList = val ? this.el_table_column.map(column => column.label) : []
      this.isIndeterminate = false
      this.updateVisibleColumns()
    },
    handleDateChange(fieldName) {
      // 如果你需要对日期变化做特殊处理，可以在这里实现
      console.log(`Date range changed for ${fieldName}:`, this.searchForm[fieldName])
      this.search()
    },
    handleCheckedColumnsChange(value) {
      const checkedCount = value.length
      this.isAllChecked = checkedCount === this.el_table_column.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.el_table_column.length
    },
    fetchData(isSearch) {
      this.listLoading = true
      api.getList(this.listQuery).then(res => {
        this.el_table_column = res.data.el_table_column
        // 初始化时将所有列设为可见，并填充到checkList中
        if (!isSearch) {
          this.el_table_column.forEach(column => this.checkList.push(column.label))
          this.updateVisibleColumns()
        }
        this.fields = res.data.search_fields
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      })
    },

    search() {
      this.listQuery.page = 1
      Object.assign(this.listQuery, this.searchForm)
      this.fetchData(true)
    },
    del(id) {
      this.$confirm('此操作将删除此分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.del({ id: id }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.fetchData()
        })
      }).catch(() => {

      })
    },
  }

}
</script>

<style>
.el-image {
  width: 46px;
  height: 46px;
}

.bs-red {
  color: #ff0000;
}

.bs-green {
  color: #089c08;
}

.action-btns {
  display: flex;
  /*两端显示*/
  justify-content: space-between;
  align-items: center;

}

.el-button + .el-button, .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: unset !important;
}
</style>
